package com.jetlion.sharedpreference;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {

        sharedPreferences = getSharedPreferences("demo", MODE_PRIVATE);

        Button writeBtn = findViewById(R.id.write_btn);

        Button readBtn = findViewById(R.id.read_btn);

        TextView textView = findViewById(R.id.text);

        writeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //获得 SharedPreferences 的 Editor 编辑器对象
                SharedPreferences.Editor edit = sharedPreferences.edit();
                int i = new Random().nextInt(1000);
                Log.i("MainActivity", "random: " + i);

                //以键值对的形式写入值
                edit.putInt("random", i);

                //提交
                edit.commit();
            }
        });

        readBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //方法原型 int getInt(String var1, int var2);
                //第二个参数var2 是默认值，当没有找到对应的value时返回的值
                int random = sharedPreferences.getInt("random", 0);
                textView.setText("the num is:" + random);
            }
        });
    }
}